'use client';

import { useState, useRef, useEffect } from 'react';
import { cn } from '@/lib/utils';
import {
  ChevronRight,
  Star,
  Heart,
  Zap,
  Sparkles,
  ArrowRight,
} from 'lucide-react';

/**
 * 动画按钮组件
 * 支持多种悬停和点击动画效果
 */
interface AnimatedButtonProps {
  children: React.ReactNode;
  className?: string;
  variant?:
    | 'default'
    | 'glow'
    | 'ripple'
    | 'magnetic'
    | 'bounce'
    | 'slide'
    | 'rotate'
    | 'scale';
  onClick?: () => void;
  disabled?: boolean;
}

export function AnimatedButton({
  children,
  className,
  variant = 'default',
  onClick,
  disabled = false,
}: AnimatedButtonProps) {
  const [isHovered, setIsHovered] = useState(false);
  const [isPressed, setIsPressed] = useState(false);
  const [ripples, setRipples] = useState<
    Array<{ id: number; x: number; y: number }>
  >([]);
  const buttonRef = useRef<HTMLButtonElement>(null);

  const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    if (disabled) return;

    setIsPressed(true);
    setTimeout(() => setIsPressed(false), 150);

    // 涟漪效果
    if (variant === 'ripple' && buttonRef.current) {
      const rect = buttonRef.current.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      const id = Date.now();

      setRipples(prev => [...prev, { id, x, y }]);

      setTimeout(() => {
        setRipples(prev => prev.filter(ripple => ripple.id !== id));
      }, 600);
    }

    onClick && onClick();
  };

  const getVariantClasses = () => {
    switch (variant) {
      case 'glow':
        return cn(
          'relative overflow-hidden transition-all duration-300',
          'bg-gradient-to-r from-blue-500 to-purple-600 text-white',
          'hover:shadow-lg hover:shadow-blue-500/25 hover:scale-105',
          'active:scale-95',
          isHovered && 'shadow-xl shadow-blue-500/40'
        );

      case 'magnetic':
        return cn(
          'transition-all duration-200 ease-out',
          'hover:scale-105 hover:-translate-y-1 hover:shadow-lg',
          'active:scale-95 active:translate-y-0'
        );

      case 'bounce':
        return cn(
          'transition-all duration-200',
          'hover:animate-bounce hover:bg-blue-50 dark:hover:bg-blue-950',
          'active:animate-pulse'
        );

      case 'slide':
        return cn(
          'relative overflow-hidden transition-all duration-300',
          'before:absolute before:inset-0 before:bg-gradient-to-r before:from-blue-500 before:to-purple-600',
          'before:translate-x-[-100%] hover:before:translate-x-0 before:transition-transform before:duration-300',
          'hover:text-white'
        );

      case 'rotate':
        return cn(
          'transition-all duration-300',
          'hover:rotate-3 hover:scale-105 hover:shadow-lg',
          'active:rotate-0 active:scale-95'
        );

      case 'scale':
        return cn(
          'transition-all duration-200',
          'hover:scale-110 hover:shadow-lg',
          'active:scale-95',
          isPressed && 'animate-pulse'
        );

      default:
        return 'transition-all duration-200 hover:bg-gray-100 dark:hover:bg-gray-800';
    }
  };

  return (
    <button
      ref={buttonRef}
      className={cn(
        'relative px-4 py-2 rounded-lg font-medium focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
        getVariantClasses(),
        disabled && 'opacity-50 cursor-not-allowed',
        className
      )}
      onClick={handleClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      disabled={disabled}
    >
      {/* 滑动背景 */}
      {variant === 'slide' && <span className="relative z-10">{children}</span>}

      {/* 发光效果 */}
      {variant === 'glow' && isHovered && (
        <div className="absolute inset-0 bg-gradient-to-r from-blue-400 to-purple-500 opacity-20 animate-pulse" />
      )}

      {/* 涟漪效果 */}
      {variant === 'ripple' && (
        <>
          {ripples.map(({ id, x, y }) => (
            <span
              key={id}
              className="absolute bg-white/30 rounded-full animate-ping"
              style={{
                left: x - 10,
                top: y - 10,
                width: 20,
                height: 20,
                animationDuration: '0.6s',
              }}
            />
          ))}
        </>
      )}

      {variant !== 'slide' && children}
    </button>
  );
}

/**
 * 动画卡片组件
 * 支持悬停、倾斜、发光等效果
 */
interface AnimatedCardProps {
  children: React.ReactNode;
  className?: string;
  variant?: 'default' | 'hover-lift' | 'tilt' | 'glow' | 'border-glow' | 'flip';
  onClick?: () => void;
}

export function AnimatedCard({
  children,
  className,
  variant = 'default',
  onClick,
}: AnimatedCardProps) {
  const [isHovered, setIsHovered] = useState(false);
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const cardRef = useRef<HTMLDivElement>(null);

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (variant === 'tilt' && cardRef.current) {
      const rect = cardRef.current.getBoundingClientRect();
      const x = (e.clientX - rect.left - rect.width / 2) / rect.width;
      const y = (e.clientY - rect.top - rect.height / 2) / rect.height;
      setMousePosition({ x, y });
    }
  };

  const getVariantClasses = () => {
    switch (variant) {
      case 'hover-lift':
        return cn(
          'transition-all duration-300 ease-out',
          'hover:shadow-xl hover:-translate-y-2 hover:scale-[1.02]',
          'active:scale-[0.98] active:translate-y-0'
        );

      case 'tilt':
        return cn(
          'transition-all duration-200 ease-out transform-gpu',
          isHovered && 'shadow-xl'
        );

      case 'glow':
        return cn(
          'relative transition-all duration-300',
          'hover:shadow-2xl hover:shadow-blue-500/20',
          'before:absolute before:inset-0 before:rounded-lg before:bg-gradient-to-r before:from-blue-500/0 before:to-purple-500/0',
          'hover:before:from-blue-500/10 hover:before:to-purple-500/10 before:transition-all before:duration-300'
        );

      case 'border-glow':
        return cn(
          'relative transition-all duration-300',
          'border border-gray-200 dark:border-gray-700',
          'hover:border-blue-500/50 hover:shadow-lg hover:shadow-blue-500/10',
          'before:absolute before:inset-0 before:rounded-lg before:bg-gradient-to-r before:from-blue-500/0 before:to-purple-500/0 before:p-[1px]',
          'hover:before:from-blue-500/20 hover:before:to-purple-500/20'
        );

      case 'flip':
        return cn(
          'transition-all duration-500 transform-gpu',
          'hover:rotate-y-12 hover:shadow-xl'
        );

      default:
        return 'transition-all duration-200 hover:shadow-md';
    }
  };

  const getTiltStyle = () => {
    if (variant === 'tilt' && isHovered) {
      return {
        transform: `perspective(1000px) rotateX(${mousePosition.y * 10}deg) rotateY(${mousePosition.x * 10}deg) translateZ(20px)`,
      };
    }
    return {};
  };

  return (
    <div
      ref={cardRef}
      className={cn(
        'bg-white dark:bg-gray-800 rounded-lg p-6 cursor-pointer',
        getVariantClasses(),
        className
      )}
      style={getTiltStyle()}
      onClick={onClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => {
        setIsHovered(false);
        setMousePosition({ x: 0, y: 0 });
      }}
      onMouseMove={handleMouseMove}
    >
      {children}
    </div>
  );
}

/**
 * 动画输入框组件
 * 支持聚焦动画、浮动标签等效果
 */
interface AnimatedInputProps {
  label?: string;
  placeholder?: string;
  value?: string;
  onChange?: (value: string) => void;
  className?: string;
  variant?: 'default' | 'floating' | 'underline' | 'glow';
  type?: 'text' | 'email' | 'password' | 'number';
}

export function AnimatedInput({
  label,
  placeholder,
  value = '',
  onChange,
  className,
  variant = 'default',
  type = 'text',
}: AnimatedInputProps) {
  const [isFocused, setIsFocused] = useState(false);
  const [hasValue, setHasValue] = useState(false);

  useEffect(() => {
    setHasValue(value.length > 0);
  }, [value]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    onChange?.(e.target.value);
  };

  if (variant === 'floating') {
    return (
      <div className={cn('relative', className)}>
        <input
          type={type}
          value={value}
          onChange={handleChange}
          onFocus={() => setIsFocused(true)}
          onBlur={() => setIsFocused(false)}
          className={cn(
            'w-full px-4 py-3 bg-transparent border border-gray-300 dark:border-gray-600 rounded-lg',
            'focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20',
            'transition-all duration-200',
            'peer'
          )}
          placeholder=" "
        />
        {label && (
          <label
            className={cn(
              'absolute left-4 transition-all duration-200 pointer-events-none',
              'text-gray-500 dark:text-gray-400',
              isFocused || hasValue
                ? '-top-2 text-xs bg-white dark:bg-gray-800 px-2 text-blue-500'
                : 'top-3 text-base'
            )}
          >
            {label}
          </label>
        )}
      </div>
    );
  }

  if (variant === 'underline') {
    return (
      <div className={cn('relative', className)}>
        <input
          type={type}
          value={value}
          onChange={handleChange}
          onFocus={() => setIsFocused(true)}
          onBlur={() => setIsFocused(false)}
          className={cn(
            'w-full px-0 py-2 bg-transparent border-0 border-b-2 border-gray-300 dark:border-gray-600',
            'focus:outline-none focus:border-blue-500',
            'transition-all duration-200'
          )}
          placeholder={placeholder}
        />
        {label && (
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {label}
          </label>
        )}
        <div
          className={cn(
            'absolute bottom-0 left-0 h-0.5 bg-blue-500 transition-all duration-200',
            isFocused ? 'w-full' : 'w-0'
          )}
        />
      </div>
    );
  }

  if (variant === 'glow') {
    return (
      <div className={cn('relative', className)}>
        {label && (
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
            {label}
          </label>
        )}
        <input
          type={type}
          value={value}
          onChange={handleChange}
          onFocus={() => setIsFocused(true)}
          onBlur={() => setIsFocused(false)}
          className={cn(
            'w-full px-4 py-3 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg',
            'focus:outline-none focus:border-blue-500 focus:ring-4 focus:ring-blue-500/20',
            'transition-all duration-200',
            isFocused && 'shadow-lg shadow-blue-500/20'
          )}
          placeholder={placeholder}
        />
      </div>
    );
  }

  return (
    <div className={cn('relative', className)}>
      {label && (
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
          {label}
        </label>
      )}
      <input
        type={type}
        value={value}
        onChange={handleChange}
        onFocus={() => setIsFocused(true)}
        onBlur={() => setIsFocused(false)}
        className={cn(
          'w-full px-4 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg',
          'focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20',
          'transition-all duration-200'
        )}
        placeholder={placeholder}
      />
    </div>
  );
}

/**
 * 动画图标组件
 * 支持旋转、弹跳、脉冲等动画效果
 */
interface AnimatedIconProps {
  icon: React.ComponentType<{ className?: string }>;
  className?: string;
  variant?: 'spin' | 'bounce' | 'pulse' | 'wiggle' | 'float' | 'glow';
  trigger?: 'hover' | 'always' | 'click';
  onClick?: () => void;
}

export function AnimatedIcon({
  icon: Icon,
  className,
  variant = 'pulse',
  trigger = 'hover',
  onClick,
}: AnimatedIconProps) {
  const [isActive, setIsActive] = useState(trigger === 'always');
  const [isClicked, setIsClicked] = useState(false);

  const handleClick = () => {
    if (trigger === 'click') {
      setIsClicked(true);
      setTimeout(() => setIsClicked(false), 600);
    }
    onClick?.();
  };

  const getAnimationClasses = () => {
    const shouldAnimate = trigger === 'always' || isActive || isClicked;

    switch (variant) {
      case 'spin':
        return shouldAnimate ? 'animate-spin' : '';
      case 'bounce':
        return shouldAnimate ? 'animate-bounce' : '';
      case 'pulse':
        return shouldAnimate ? 'animate-pulse' : '';
      case 'wiggle':
        return shouldAnimate ? 'animate-[wiggle_1s_ease-in-out_infinite]' : '';
      case 'float':
        return shouldAnimate ? 'animate-[float_3s_ease-in-out_infinite]' : '';
      case 'glow':
        return shouldAnimate
          ? 'animate-pulse drop-shadow-[0_0_8px_rgba(59,130,246,0.5)]'
          : '';
      default:
        return '';
    }
  };

  return (
    <div
      className={cn(
        'inline-block transition-all duration-200',
        trigger === 'hover' && 'hover:scale-110',
        trigger === 'click' && 'cursor-pointer active:scale-95',
        className
      )}
      onMouseEnter={() => trigger === 'hover' && setIsActive(true)}
      onMouseLeave={() => trigger === 'hover' && setIsActive(false)}
      onClick={handleClick}
    >
      <Icon className={cn('w-6 h-6', getAnimationClasses())} />
    </div>
  );
}

/**
 * 动画列表项组件
 * 支持交错动画、滑入效果等
 */
interface AnimatedListProps {
  children: React.ReactNode[];
  className?: string;
  variant?: 'fade-in' | 'slide-in' | 'scale-in' | 'stagger';
  delay?: number;
}

export function AnimatedList({
  children,
  className,
  variant = 'fade-in',
  delay = 100,
}: AnimatedListProps) {
  const [visibleItems, setVisibleItems] = useState<number[]>([]);

  useEffect(() => {
    children.forEach((_, index) => {
      setTimeout(() => {
        setVisibleItems(prev => [...prev, index]);
      }, index * delay);
    });
  }, [children, delay]);

  const getItemClasses = (index: number) => {
    const isVisible = visibleItems.includes(index);

    switch (variant) {
      case 'slide-in':
        return cn(
          'transition-all duration-500 ease-out',
          isVisible ? 'translate-x-0 opacity-100' : 'translate-x-8 opacity-0'
        );
      case 'scale-in':
        return cn(
          'transition-all duration-500 ease-out',
          isVisible ? 'scale-100 opacity-100' : 'scale-95 opacity-0'
        );
      case 'stagger':
        return cn(
          'transition-all duration-700 ease-out',
          isVisible ? 'translate-y-0 opacity-100' : 'translate-y-4 opacity-0'
        );
      default:
        return cn(
          'transition-all duration-500 ease-out',
          isVisible ? 'opacity-100' : 'opacity-0'
        );
    }
  };

  return (
    <div className={cn('space-y-4', className)}>
      {children.map((child, index) => (
        <div key={index} className={getItemClasses(index)}>
          {child}
        </div>
      ))}
    </div>
  );
}

/**
 * 悬停效果组件
 * 为任何元素添加悬停动画效果
 */
interface HoverEffectProps {
  children: React.ReactNode;
  className?: string;
  effect?: 'lift' | 'glow' | 'tilt' | 'zoom' | 'shake' | 'rotate';
  intensity?: 'subtle' | 'medium' | 'strong';
}

export function HoverEffect({
  children,
  className,
  effect = 'lift',
  intensity = 'medium',
}: HoverEffectProps) {
  const getIntensityValue = () => {
    switch (intensity) {
      case 'subtle':
        return 1;
      case 'strong':
        return 3;
      default:
        return 2;
    }
  };

  const getEffectClasses = () => {
    const level = getIntensityValue();

    switch (effect) {
      case 'lift':
        return `hover:-translate-y-${level} hover:shadow-lg`;
      case 'glow':
        return `hover:shadow-lg hover:shadow-blue-500/${level * 10}`;
      case 'tilt':
        return `hover:rotate-${level}`;
      case 'zoom':
        return `hover:scale-${100 + level * 5}`;
      case 'shake':
        return 'hover:animate-[shake_0.5s_ease-in-out]';
      case 'rotate':
        return `hover:rotate-${level * 2}`;
      default:
        return '';
    }
  };

  return (
    <div
      className={cn(
        'transition-all duration-200 ease-out',
        getEffectClasses(),
        className
      )}
    >
      {children}
    </div>
  );
}

/**
 * 点击波纹效果组件
 */
interface RippleEffectProps {
  children: React.ReactNode;
  className?: string;
  color?: string;
  duration?: number;
}

export function RippleEffect({
  children,
  className,
  color = 'rgba(255, 255, 255, 0.6)',
  duration = 600,
}: RippleEffectProps) {
  const [ripples, setRipples] = useState<
    Array<{
      id: number;
      x: number;
      y: number;
      size: number;
    }>
  >([]);
  const containerRef = useRef<HTMLDivElement>(null);

  const createRipple = (e: React.MouseEvent) => {
    if (!containerRef.current) return;

    const rect = containerRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    const size = Math.max(rect.width, rect.height) * 2;
    const id = Date.now();

    setRipples(prev => [...prev, { id, x, y, size }]);

    setTimeout(() => {
      setRipples(prev => prev.filter(ripple => ripple.id !== id));
    }, duration);
  };

  return (
    <div
      ref={containerRef}
      className={cn('relative overflow-hidden', className)}
      onClick={createRipple}
    >
      {children}
      {ripples.map(({ id, x, y, size }) => (
        <span
          key={id}
          className="absolute rounded-full animate-ping pointer-events-none"
          style={{
            left: x - size / 2,
            top: y - size / 2,
            width: size,
            height: size,
            backgroundColor: color,
            animationDuration: `${duration}ms`,
          }}
        />
      ))}
    </div>
  );
}
